package com.richard.base.util

import android.content.Context
import android.graphics.Typeface
import java.lang.reflect.Field


/**
 ***************************************
 * 项目名称:Giggle
 * @Author wuzhiguo
 * 邮箱：wuzhiguo@ksjgs.com
 * 创建时间: 2020/8/8     7:53 PM
 * 用途:
 ***************************************
 */

object FontsOverride {
    /**
     * 设置默认字体
     *
     * @param context
     * @param staticTypefaceFieldName
     * @param fontAssetName
     */
    fun setDefaultFont(
        context: Context,
        staticTypefaceFieldName: String?,
        fontAssetName: String?
    ) {
        val regular = Typeface.createFromAsset(context.assets, fontAssetName)
        replaceFont(staticTypefaceFieldName, regular)
    }

    /**
     * 替换字体
     *
     * @param staticTypefaceFieldName
     * @param newTypeface
     */
    private fun replaceFont(
        staticTypefaceFieldName: String?,
        newTypeface: Typeface?
    ) {
        try {
            val staticField: Field =
                Typeface::class.java.getDeclaredField(staticTypefaceFieldName!!)
            staticField.isAccessible = true
            staticField.set(null, newTypeface)
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
    }
}